package com.sd.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;

import com.sd.util.HttpUtil;
import com.sd.util.StringUtils;
import com.snda.woa.android.OpenAPI;
import com.snda.woa.android.callback.AutoLoginCallBack;
import com.snda.woa.android.callback.PwdLoginCallBack;

/**
 * 
 * @author Alex.Lu
 * 
 */
public class EBookActivity extends Activity implements OnClickListener,
		OnCancelListener, AutoLoginCallBack, PwdLoginCallBack {

	private final String TAG = "EBookActivity";
	private static final int DIALOG_LIST_CHARGE = 0;
	private static final int DIALOG_CHARGE = 1;
	private static final int DIALOG_LOGIN = 2;

	public static String user = "&from=az01";
	private WebView mWebView;
	private WebSettings mWebSettings;

	private Button mStackBT;
	private Button mVoucherBT;
	private Button mLoginBT;
	private Button mIndexBT;
	private Button mClassifyBT;
	private Button mRankBT;
	private Button mStudyBT;
	private Button mSearchBT;
	private ProgressDialog mProgressDialog;

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (mWebView.canGoBack()) {
			mWebView.goBack();
		} else {
			super.onBackPressed();
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		user = "&from=az01";
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.e_book_activity);
		mWebView = (WebView) this.findViewById(R.id.webview);
		// CookieManager.getInstance().removeExpiredCookie();
		// 设置支持JavaScript等
		mWebSettings = mWebView.getSettings();
		mWebSettings.setJavaScriptEnabled(true);
		// mWebSettings.setBuiltInZoomControls(true);
		mWebSettings.setLightTouchEnabled(true);
		mWebSettings.setSupportZoom(false);
		// mWebSettings.setTextSize(TextSize.LARGER);
		mWebView.setHapticFeedbackEnabled(false);
		WebViewClientDemo client = new WebViewClientDemo();
		mWebView.setWebViewClient(client);
		String url = getSid("http://221.181.69.31:9201/wap2/index.do?");
		mWebView.loadUrl(url);
		mStackBT = (Button) findViewById(R.id.stack_btn);
		mStackBT.setOnClickListener(this);
		mVoucherBT = (Button) findViewById(R.id.voucher_btn);
		mVoucherBT.setOnClickListener(this);
		mLoginBT = (Button) findViewById(R.id.login_btn);
		mLoginBT.setOnClickListener(this);
		mIndexBT = (Button) findViewById(R.id.index_btn);
		mIndexBT.setOnClickListener(this);
		mClassifyBT = (Button) findViewById(R.id.classify_btn);
		mClassifyBT.setOnClickListener(this);
		mRankBT = (Button) findViewById(R.id.rank_btn);
		mRankBT.setOnClickListener(this);
		mStudyBT = (Button) findViewById(R.id.study_btn);
		mStudyBT.setOnClickListener(this);
		mSearchBT = (Button) findViewById(R.id.search_btn);
		mSearchBT.setOnClickListener(this);
		OpenAPI.init(EBookActivity.this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int v_id = v.getId();
		switch (v_id) {
		case R.id.mobileLogin:
			Intent intent = new Intent();
			intent.setClass(this, MobileReginWithSVR.class);
			startActivity(intent);
			//OpenAPI.mobileAutoLogin(new d(), true, EBookActivity.this, null);
			break;
		case R.id.stack_btn:
			finish();
			break;
		case R.id.voucher_btn:
			showDialog(DIALOG_LIST_CHARGE);
			break;
		case R.id.login_btn:
			showDialog(DIALOG_LOGIN);
			break;
		case R.id.index_btn:
			String url = getSid("http://221.181.69.31:9201/wap2/index.do?");
			Log.d("", "url:" + url);
			mWebView.loadUrl(url);
			break;
		case R.id.classify_btn:
			mWebView
					.loadUrl(getSid("http://221.181.69.31:9201/wap2/book/bookcategory.do?mtd=bookcategory&fromindex=lm5"));
			break;
		case R.id.rank_btn:
			mWebView
					.loadUrl(getSid("http://221.181.69.31:9201/wap2/top/index.do?fromindex=lm4"));
			break;
		case R.id.study_btn:
			mWebView
					.loadUrl(getSid("http://221.181.69.31:9201/wap2/user/mybookroom.do?userId=0&type=2&mtd=myBookRoom&fromindex=lm0"));
			break;
		case R.id.search_btn:
			mWebView
					.loadUrl(getSid("http://221.181.69.31:9201/wap2/book/booksearch_do.do?fromindex=ss0"));
			break;
		/*
		 * case R.id.auto_findbook_btn: dismissDialog(id);
		 */
		default:
			break;
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_LIST_CHARGE:
			return new AlertDialog.Builder(EBookActivity.this).setTitle("充值方式")
					.setItems(R.array.recharge_methods,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									switch (which) {
									case 0:
										Intent intent = new Intent();
										startActivity(ChargeActivity
												.getPhonePayPal(EBookActivity.this));
										break;
									case 1:
										startActivity(ChargeActivity
												.getPhoneCMCC(EBookActivity.this));
										break;
									case 2:
										startActivity(ChargeActivity
												.getPhoneCMCC(EBookActivity.this));
										break;
									case 3:
									case 4:
									case 5:
									case 6:
										showDialog(DIALOG_CHARGE);
										break;

									default:
										break;
									}
								}
							}).create();
		case DIALOG_CHARGE:
			return new AlertDialog.Builder(EBookActivity.this)
					.setTitle("确定充值？").setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									/* User clicked OK so do some stuff */
									SmsManager manage = SmsManager.getDefault();
									manage.sendTextMessage("13655712549",
											"10086", "oxx", null, null);
								}
							}).setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked Cancel so do some stuff */
								}
							}).create();
		case DIALOG_LOGIN:
			// This example shows how to add a custom layout to an AlertDialog
			LayoutInflater factory = LayoutInflater.from(this);
			final View textEntryView = factory.inflate(
					R.layout.alert_dialog_text_entry, null);
			Button but = (Button) textEntryView.findViewById(R.id.mobileLogin);
			
			but.setOnClickListener(this);
			return new AlertDialog.Builder(EBookActivity.this).setTitle("用户登录")
					.setView(textEntryView).setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									String pt = ((EditText)textEntryView.findViewById(R.id.username_edit)).getText().toString().trim();
									String pwd = ((EditText)textEntryView.findViewById(R.id.password_edit)).getText().toString().trim();
									Log.d(TAG, "pt:"+pt+"  pwd:"+pwd);
									OpenAPI.pwdLogin(EBookActivity.this, pt, pwd, false, false, EBookActivity.this, null);
									/* User clicked OK so do some stuff */
								}
							}).setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									/* User clicked cancel so do some stuff */
								}
							}).create();
		}
		return null;

	}

	private String getSid(String url) {
		StringBuffer sbuf = new StringBuffer();
		sbuf.append(url);

		if(!user.equals("&from=az01")){
			sbuf.append("&sid=");
		}
		sbuf.append(user);
		Log.e(TAG, sbuf.toString());
		return sbuf.toString();
	}

	private class WebViewClientDemo extends WebViewClient {

		@Override
		// 在WebView中而不是默认浏览器中显示页面
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			/*
			 * mProgressDialog = ProgressDialog.show(EBookActivity.this,
			 * null,url); mProgressDialog.setCancelable(true);
			 * mProgressDialog.setOnCancelListener(EBookActivity.this);
			 * Log.d(TAG, "url:"+url);
			 */
			view.loadUrl(url);
			return true;
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// TODO Auto-generated method stub
			mProgressDialog = ProgressDialog.show(EBookActivity.this, null, "");
			mProgressDialog.setCancelable(true);
			mProgressDialog.setOnCancelListener(EBookActivity.this);
			super.onPageStarted(view, getSid(url), favicon);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			mProgressDialog.dismiss();
			super.onPageFinished(view, url);
		}

		@Override
		public void onLoadResource(WebView view, String url) {
			// TODO Auto-generated method stub
			super.onLoadResource(view, url);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			// TODO Auto-generated method stub
			mProgressDialog.dismiss();
			super.onReceivedError(view, errorCode, description, failingUrl);
		}
	}
	
	

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		CookieManager.getInstance().removeAllCookie();
		super.onDestroy();
	}

	@Override
	public void onCancel(DialogInterface dialog) {
		// TODO Auto-generated method stub
		mWebView.stopLoading();
		mProgressDialog.dismiss();
	}

	// 登录令牌
	protected String token;
	// sessionId验证返回结果码
	protected String resultCode;

	
	@Override
	public void callBack(int code, String message, String sessionId) {
		
		
		Log.d(TAG, "PwdLoginSdkUiActivity callBack start ...");

		if (mProgressDialog.isShowing()) {
			mProgressDialog.cancel();
		}
		// sessionId由sdk回调返回
		if (StringUtils.checkCallBackStat(code, sessionId)) {
			// 通过应用自身服务端与woa服务端进行sessionId验证（此步骤是判断登录成功与否的关键）
			String result = HttpUtil.readStringFromUrl("20008", sessionId, "utf-8", new Object());
			Log.e(TAG, "result: " + result + " \n");
			mWebView.loadUrl(getSid(mWebView.getUrl()));
			if (result != null) {
				EBookActivity.user = StringUtils.getValueByKey(result, "sid");
				token = StringUtils.getValueByKey(result, "proxyTicket");
				resultCode = StringUtils.getValueByKey(result, "resultCode");
				if (!StringUtils.isEmpty(token) && "0".equals(resultCode)) {
					
					// 验证完sessionId后不管成功与否，都需要反馈给sdk
					// 调用反馈接口（接口参数：应用上下文，是否登录成功，sessionId验证返回的结果码，验证获取的token）
					// sessionId验证成功即可认为是此次登录成功
					OpenAPI.loginFeedBack(EBookActivity.this, true, resultCode != null ? Integer.valueOf(resultCode) : -1, token);
				} else {
					// sessionId验证失败“是否登录成功”请使用false
					OpenAPI.loginFeedBack(EBookActivity.this, false, resultCode != null ? Integer.valueOf(resultCode) : -1, token);
				}
			} else {
				// sessionId验证返回的状态码没有请使用-1代替
				OpenAPI.loginFeedBack(EBookActivity.this, true, -1, token);
			}

			if (!StringUtils.isEmpty(token)) {
				Log.d(TAG, "token: " + token + " \n");
			}

		} else {
		}

	}

	@Override
	public void eCardCallBack(int arg0, String arg1, String arg2, String[] arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void eKeyCallBack(int arg0, String arg1, String arg2, String arg3) {
		// TODO Auto-generated method stub
		
	}
	
	
	private class d implements AutoLoginCallBack{

		@Override
		public void callBack(int code, String message, String sessionId) {
			// TODO Auto-generated method stub
			// TODO Auto-generated method stub
			Log.d(TAG, "MobileAutoLoginSdkUiActivity callBack start...");
			Log.i(TAG, "OpenAPI.loginStat " + message);
			Log.i(TAG, "OpenAPI.getMsg() " + OpenAPI.getStatusText(code));
			if (StringUtils.checkCallBackStat(code, sessionId)) {
				Log.i(TAG, "OpenAPI.getSessionId() " + sessionId);
				// 通过应用自身服务端与woa服务端进行sessionId验证（此步骤是判断登录成功与否的关键）
				String ret = HttpUtil.readStringFromUrl("20008",
						sessionId, "UTF-8");
				Log.d(TAG, "result: " + ret + " \n");
				if (!StringUtils.isEmpty(ret)) {
					token = StringUtils.getValueByKey(ret, "token");
					resultCode = StringUtils.getValueByKey(ret, "resultCode");
					if (!StringUtils.isEmpty(token) && "0".equals(resultCode)) {
						// 验证完sessionId后不管成功与否，都需要反馈给sdk
						// 调用反馈接口（接口参数：应用上下文，是否登录成功，sessionId验证返回的结果码，验证获取的token）
						// sessionId验证成功即可认为是此次登录成功
						OpenAPI.loginFeedBack(EBookActivity.this, true,
								resultCode != null ? Integer.valueOf(resultCode)
										: -1, token);
					} else {
						// sessionId验证失败“是否登录成功”请使用false
						OpenAPI.loginFeedBack(EBookActivity.this, false,
								resultCode != null ? Integer.valueOf(resultCode)
										: -1, token);
					}
				} else {
					// sessionId验证返回的状态码没有请使用-1代替
					OpenAPI.loginFeedBack(EBookActivity.this, false, -1, token);
				}
			} else {
				// sdk逻辑处理出现异常
			}
			if (!StringUtils.isEmpty(token)) {
				Log.d(TAG, "token: " + token + " \n");
			} else {
			}
		}
		
	}

}